package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

var DB *gorm.DB
var mysqlLogger logger.Interface

func init() {
	username := "root"
	//password := "xhsd_dev@20180810"
	password := "Qdyyxx08@@"
	//host := "localhost"
	host := "47.92.141.186"
	port := "3338"
	dbname := "gorm"
	timeout := "10s"
	//dsn := "root:root@tcp(127.0.0.1:3306)/test?charset=utf8"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local&timeout=%s", username, password, host, port, dbname, timeout)

	//mysqlLogger = logger.Default.LogMode(logger.Info)//lv
	mysqlLogger = logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Second, //慢SQL阈值 1s
			LogLevel:                  logger.Info,
			Colorful:                  true,
			IgnoreRecordNotFoundError: true, //忽略未找到记录的错误
		},
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "t_",  //表的前缀
			SingularTable: true,  //单数表名，还是复数表名
			NoLowerCase:   false, //要不要小写
		},
		//Logger: mysqlLogger,
	})
	if err != nil {
		panic("fail to conn db, err=" + err.Error())
	}

	fmt.Println("conn success")

	sqlDB, err := db.DB()
	if err != nil {
		panic("Failed to get db: " + err.Error())
	}
	sqlDB.SetMaxIdleConns(10)           // 设置数据库的最大空闲连接
	sqlDB.SetMaxOpenConns(100)          // 设置数据库的最大连接数量
	sqlDB.SetConnMaxLifetime(time.Hour) // 设置连接的最大可复用时间

	fmt.Println(db)
	DB = db
}

// Student 字段如果需要nullable，需要使用指针
type Student struct {
	ID       uint      `gorm:"size:10;primaryKey;autoIncrement"`
	Name     string    `gorm:"size:20;not null"`
	Age      int       `gorm:"size:3;default:0"`
	Email    *string   `gorm:"size:255;unique"`
	Birthday time.Time `gorm:"type:datetime;default:CURRENT_TIMESTAMP;comment:生日"`
}

func main01() {
	fmt.Println(DB)

	DB.AutoMigrate(&Student{}) //只新增，或者修改大小，不会删除

	//部分展示日志
	session := DB.Session(&gorm.Session{Logger: mysqlLogger})
	student := Student{}
	tx := session.First(&student)
	if tx.Error != nil {
		fmt.Println(tx.Error)
	} else {
		fmt.Println(student)
	}

	//主动日志
	//DB.Debug().First(student)
}
